package com.example.springbootthreadexamples.thread;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author LanWP
 * @date 2024-08-05
 */
public class TransmittableThreadLocalDemo {

    public static ThreadLocal<Map<String, Object>> threadLocal = new TransmittableThreadLocal<>();
    public static ExecutorService executorService =
            TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(1));

    public static ExecutorService executorService1 =
            TtlExecutors.getTtlExecutorService(
                    new ThreadPoolExecutor(20, 200, 60000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1000))
            );

    public static void main(String[] args) throws InterruptedException {
        System.out.println("主线程开启");
        HashMap<String, Object> map = new HashMap<>(4);
        map.put("name", "fandf");
        threadLocal.set(map);
        System.out.println("主线程读取本地变量：" + threadLocal.get().get("name"));

        executorService.submit(() -> {
            System.out.println("子线程读取本地变量：" + threadLocal.get().get("name"));
        });

        TimeUnit.SECONDS.sleep(1);

        threadLocal.get().put("name", "ffff");
        System.out.println("主线程读取本地变量：" + threadLocal.get().get("name"));

        executorService.submit(() -> {
            //[读到了主线程修改后的新值]
            System.out.println("子线程读取本地变量：" + threadLocal.get().get("name"));
            threadLocal.get().put("name", "dddd");
            System.out.println("子线程读取本地变量：" + threadLocal.get().get("name"));
        });

        TimeUnit.SECONDS.sleep(1);
        System.out.println("主线程读取本地变量：" + threadLocal.get().get("name"));
    }
    // 原文链接：https://blog.csdn.net/qq_14946371/article/details/129321109
}
